package cn.yunyichina.provider.order.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.BoneService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.order.dao.OrderBoneExtendDao;
import cn.yunyichina.provider.order.entity.OrderBoneExtend;
import cn.yunyichina.utils.convert.JsonUtils;

@Service("boneExtendServiceImpl")
public class BoneExtendServiceImpl {
    private Logger logger = LoggerFactory.getLogger(BoneExtendServiceImpl.class);

    @Autowired
    private OrderBoneExtendDao orderBoneExtendDao;

    /**
     * yyt.order.bone.extend.add
     *
     * @param data
     * @param sessionId
     * @return
     */
    public Response addBoneExtend(String data, String sessionId) {
        try {
            logger.debug("添加订单拓展信息, 入参data=" + data);
            OrderBoneExtend obeVo = JsonUtils.parseObject(data, OrderBoneExtend.class);
            orderBoneExtendDao.insert(obeVo);
            return Response.success();
        } catch (Exception e) {
            logger.error("添加订单拓展信息报错", e);
            return Response.failure();
        }
    }

    /**
     * yyt.order.bone.extend.update
     *
     * @param data
     * @return
     */
    public ResponseObject updateBoneExtend(String data) {
        ResponseObject responseObject = new ResponseObject();
        try {
            OrderBoneExtend orderBoneExtend = JsonUtils.parseObject(data, OrderBoneExtend.class);
            if (StringUtils.isBlank(orderBoneExtend.getOrderNo())) {
                responseObject.setResultCodeAndMessage("1001", "请求参数order_no 缺失");
                return responseObject;
            }
            /**更新主表*/
            OrderExtVo extVo = BaseService.updateOrder(data);
            if (extVo==null){
                responseObject.setResultCodeAndMessage("1001","订单不存在");
                return responseObject;
            }
            /**更新订单拓展表*/
            orderBoneExtendDao.updateOrderBoneExtendByOrderNo(orderBoneExtend);
            responseObject.setResultCodeAndMessage("0", "成功");
            
            Short orderStatus = extVo.getOrderStatus();
            final String orderNo = extVo.getOrderNo();
            if (orderStatus != null && orderStatus == 98) {
            	// 发送消息给患者
            	new Thread(new Runnable() {
					
					@Override
					public void run() {
						// yyt.bone.bone.msg.cancel.order.send
						BoneService.callHumpFromInternal("yyt.bone.bone.msg.cancel.order.send", "{\"order_no\":\"" + orderNo + "\"}");
					}
				}).start();
            }
            
            return responseObject;
        } catch (Exception e) {
            logger.error("更新骨科拓展表出错:", e);
            responseObject.setResultCodeAndMessage("16999", "系统异常请联系管理员");
            return responseObject;
        }

    }


    /**
     * yyt.order.bone.extend.by.order.no.update
     *
     * @param data 根据id更新订单  (会诊意见，手术时间，手术服务费，拒绝/接受订单等）
     * @return
     */
    public ResponseObject updateBoneExtendByOrderNo(String data) {
        ResponseObject responseObject = new ResponseObject();
        try {
            OrderBoneExtend orderBoneExtend = JsonUtils.parseObject(data, OrderBoneExtend.class);
            if (StringUtils.isBlank(orderBoneExtend.getOrderNo())) {
                responseObject.setResultCodeAndMessage("1001", "请求参数order_no 缺失");
                return responseObject;
            }
            orderBoneExtendDao.updateOrderBoneExtendByOrderNo(orderBoneExtend);
            responseObject.setResultCodeAndMessage("0", "提交成功");
            return responseObject;
        } catch (Exception e) {
            logger.error("更新骨科拓展表出错:", e);
            responseObject.setResultCodeAndMessage("16999", "系统异常请联系管理员");
            return responseObject;
        }

    }

    /**
     * yyt.order.bone.extend.appointment.doctor.recv.sum
     *
     * @param data 根据id获取专家收入总和
     * @return
     */
    public ResponseObject sumBoneExtendAppointmentDoctorRecv(String data) {

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        ResponseObject responseObject = new ResponseObject();
        try {
            String appointmentDoctorId = maps.get("appointment_doctor_id");
            String monthDate = maps.get("month_date");//2017-03
            if (StringUtils.isBlank(appointmentDoctorId)) {
                responseObject.setResultCodeAndMessage("1001", "请求参数appointment_doctor_id 缺失");
                return responseObject;
            }

            if (StringUtils.isBlank(monthDate)) {
                responseObject.setResultCodeAndMessage("1001", "请求参数 month_date 缺失");
                return responseObject;
            }

            Map<String, String> params = new HashMap<>();
            params.put("appointmentDoctorId", appointmentDoctorId);
            params.put("monthDate", monthDate + "%");
            String recvAmount = orderBoneExtendDao.sumAppointmentDoctorRecvAmount(params);
            if (StringUtils.isBlank(recvAmount)) {
                recvAmount = "0";
            }
            responseObject.setResultObject(recvAmount + "");

            return responseObject;
        } catch (Exception e) {
            logger.error("根据id获取专家收入总和出错:", e);
            responseObject.setResultCodeAndMessage("16999", "系统异常请联系管理员");
            return responseObject;
        }

    }

    /**
     * yyt.order.bone.extend.professor.doctor.recv.sum
     *
     * @param data 根据id获取医生收入总和
     * @return
     */
    public ResponseObject sumBoneExtendProfessorDoctorRecv(String data) {

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        ResponseObject responseObject = new ResponseObject();
        try {
            String professorDoctorId = maps.get("professor_doctor_id");
            String monthDate = maps.get("month_date");//2017-03
            if (StringUtils.isBlank(professorDoctorId)) {
                responseObject.setResultCodeAndMessage("1001", "请求参数 professorDoctorId 缺失");
                return responseObject;
            }

            if (StringUtils.isBlank(monthDate)) {
                responseObject.setResultCodeAndMessage("1001", "请求参数 month_date 缺失");
                return responseObject;
            }

            Map<String, String> params = new HashMap<>();
            params.put("professorDoctorId", professorDoctorId);
            params.put("monthDate", monthDate + "%");
            String recvAmount = orderBoneExtendDao.sumProfessorDoctorRecvAmount(params);
            if (StringUtils.isBlank(recvAmount)) {
                recvAmount = "0";
            }
            responseObject.setResultObject(recvAmount);

            return responseObject;
        } catch (Exception e) {
            logger.error("根据id获取医生收入总和:", e);
            responseObject.setResultCodeAndMessage("16999", "系统异常请联系管理员");
            return responseObject;
        }

    }

    /**
     * yyt.order.bone.extend.by.id.update
     *
     * @param data 根据id更新订单  (会诊意见，手术时间，手术服务费，拒绝/接受订单等）
     * @return
     */
    public ResponseObject updateBoneExtendById(String data) {
        ResponseObject responseObject = new ResponseObject();
        try {
            OrderBoneExtend orderBoneExtend = JsonUtils.parseObject(data, OrderBoneExtend.class);
            if (StringUtils.isBlank(orderBoneExtend.getId())) {
                responseObject.setResultCodeAndMessage("1001", "请求参数id 缺失");
                return responseObject;
            }
            orderBoneExtendDao.update(orderBoneExtend);
            responseObject.setResultCodeAndMessage("0", "提交成功");
            return responseObject;
        } catch (Exception e) {
            logger.error("根据id更新订单出错:", e);
            responseObject.setResultCodeAndMessage("16999", "系统异常请联系管理员");
            return responseObject;
        }

    }


    /**
     * 根据条件获取骨科扩展订单
     * @param data
     * @interfaceName: yyt.order.bone.extend.get
     * @return
     */
    public Response getBoneExtend(String data) {
        Response response = new Response();
        try {
            logger.debug("获取骨科订单拓展信息, 入参data=" + data);
            OrderBoneExtend obeVo = JsonUtils.parseObject(data, OrderBoneExtend.class);
            List<OrderBoneExtend> orderBones = orderBoneExtendDao.select(obeVo);
            response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(orderBones));
        } catch (Exception e) {
            logger.error("添加订单拓展信息报错", e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE , Response.FAILURE_MESSAGE);
        }

        return response;
    }
}
